/**
 * Copyright (C), 2015-2019, XXX有限公司
 * FileName: LoginIntercept
 * Author:   zhouheng
 * Date:     2019/4/17 7:43
 * Description: 拦截器
 * History:
 * <author>          <time>          <version>          <desc>
 * 作者姓名           修改时间           版本号              描述
 */
package com.portal.intercepter;

import com.alibaba.fastjson.JSONObject;
import com.portal.support.BaseController;
import com.portal.support.annotation.Anonymous;
import com.portal.utils.CookieUtil;
import org.apache.commons.lang.StringUtils;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;

/**
 * 〈一句话功能简述〉<br> 
 * 〈拦截器〉
 *
 * @author zhouheng
 * @create 2019/4/17
 * @since 1.0.0
 */
public class LoginIntercept extends HandlerInterceptorAdapter {
    private final String ACCESS_TOKEN="access_token";


    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        HandlerMethod handlerMethod = (HandlerMethod)handler;
        Object action = handlerMethod.getBean();
        if(!(action instanceof BaseController)){
            throw new Exception("异常");
        }

        if(isAnonymous(handlerMethod)){
            return true;
        }

        String accessToken = CookieUtil.getCookieValue(request,ACCESS_TOKEN);

        if (StringUtils.isEmpty(accessToken)){
            if (CookieUtil.isAjax(request)){
                JSONObject object=new JSONObject();
                object.put("code","-1");
                object.put("msg","没有登录");
                response.getWriter().write(object.toJSONString());
                return false;
            }

            response.sendRedirect("/login.shtml");
            return false;
        }

        CheckAuthRequest checkAuthRequest=new CheckAuthRequest();
        checkAuthRequest.setToken(accessToken);

        CheckAuthResponse ru=userCoreService.checkAuth(checkAuthRequest);
        if("000000".equals(ru.getCode())){
            ((BaseController)action).setUid(ru.getUid());
            return true;
        }
        return false;
    }

    private boolean isAnonymous(HandlerMethod handlerMethod) {
        Object action=handlerMethod.getBean();
        Class clazz=action.getClass();
        if(clazz.getAnnotation(Anonymous.class)!=null){
            return true;
        }
        Method method=handlerMethod.getMethod();
        return method.getAnnotation(Anonymous.class)!=null;
    }
}